package com.zbkj.crmeb.chant.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crmeb.core.exception.CrmebException;
import com.zbkj.crmeb.chant.dao.ChannelMerchantPurchaseDao;
import com.zbkj.crmeb.chant.model.ChannelMerchantPurchase;
import com.zbkj.crmeb.chant.service.ChannelMerchantExperienceService;
import com.zbkj.crmeb.chant.service.ChannelMerchantPurchaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class ChannelMerchantPurchaseServiceImpl extends ServiceImpl<ChannelMerchantPurchaseDao, ChannelMerchantPurchase> implements ChannelMerchantPurchaseService {

    @Autowired
    private ChannelMerchantExperienceService channelMerchantExperienceService;

    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class, CrmebException.class})
    public Boolean success(String orderId, Integer uid, String outOrderId) {
        // 商户二维码付款成功后
        ChannelMerchantPurchase one = this.getOne(Wrappers.<ChannelMerchantPurchase>lambdaQuery().eq(ChannelMerchantPurchase::getOrderId, orderId).last("limit 1"));
        if (Objects.isNull(one) || one.getPayStatus()) {
            log.error("支付回调异常，购买产品与服务订单id：{}", orderId);
            return false;
        }
        // 更新购买订单
        one.setPayStatus(true);
        one.setOutOrderId(outOrderId);
        one.setPayTime(new Date());
        this.updateById(one);
        // 变更用户角色与商户类型，生成续费记录
        return channelMerchantExperienceService.changeExperienceType(one.getMerId(), one.getProductType(), true);
    }
}
